package org.github.project.zk.useage;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.imps.CuratorFrameworkState;
import org.apache.curator.retry.RetryOneTime;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;

/**
 * @auther yang
 * @date 2022/1/22 17:04
 */
public class CuratorOperationDemo {
    public static void main(String[] args) throws Exception {
        CuratorFramework client = connect();
        System.out.println(getClientState(client));
//        create(client, "/hello/1", "123");
    }

    // 创建 zookeeper 客户端并连接到服务器
    public static CuratorFramework connect() {
        // 创建 zookeeper 客户端
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("123.57.9.58")
                .sessionTimeoutMs(10000)
                .retryPolicy(new RetryOneTime(5000))
                .build();
        // 启动客户端
        client.start();
        return client;
    }

    // 获得客户端的状态
    public static CuratorFrameworkState getClientState(CuratorFramework client) {
        return client.getState();
    }

    // 创建结点
    public static void create(CuratorFramework client, String path, String data) throws Exception {
        String ret = client.create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.PERSISTENT)
                .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
                .forPath(path, data.getBytes());
        System.out.println("result: " + ret);
    }

    //
}
